package cn.wolfcode.rbac.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import lombok.Getter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * 封装JWT的工具类
 */
@Component
@Getter
public class JwtUtils {

    @Value("${jwt.secret}")
    private String secret;
    @Value("${jwt.header}")
    private String header;

    /**
     * @return 返回签名
     */
    public String getSecret(){
        return secret;
    }

    /**
     * 创建token
     * @param payload  map封装多个payload
     * @return  token
     */
    public String createTokenByPayloadMapType(Map<String,String> payload){
        //构建jwt对象
        JWTCreator.Builder builder = JWT.create();
        //jwt的payload部分
        payload.forEach((key,value)->builder.withClaim(key,value));
        //jwt的sign签名 后生成token
        String token = builder.sign(Algorithm.HMAC256(secret));
        return token;
    }

    /**
     * 创建token
     * @param key  payload的key
     * @param value payload的value
     * @return token
     */
    public String createTokenByPayloadString(String key,String value){
        String token = JWT.create()
                .withClaim(key, value)
                .sign(Algorithm.HMAC256(secret));
        return token;
    }

    /**
     * 根据key返回token中的payload
     * @param token token
     * @param key   要根据该key去获取值
     * @return value 返回的payload的value
     */
    public String getPayload(String token,String key){
        //1.验证签名
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(secret)).build();
        //2.验证token
        DecodedJWT decodedJWT = jwtVerifier.verify(token);
        //3.通过解析token去返回payload
        String value = decodedJWT.getClaim(key).asString();
        return value;
    }

}
